package com.duoduo.common.api.help;


import com.duoduo.common.api.constants.Constant;
import com.duoduo.common.api.constants.SerializationType;
import com.duoduo.common.api.myinterface.SerializationOperator;
import com.duoduo.common.api.spi.extension.ExtensionLoader;

import java.io.Serializable;

public class SerializationInnerUtil {
	
	private static String serializationType = SpringContextInnerUtil.get(Constant.SERIALIZATION_TYPE);
	private static SerializationOperator serializationOperator = ExtensionLoader.getExtensionLoader(SerializationOperator.class).getExtension(serializationType);
	
	public static <T extends Serializable> byte[] encode(T obj) {
        return serializationOperator.encode(obj);
    }

    public static <T extends Serializable> T decode(byte[] bytes, Class<T> clazz) {
        return serializationOperator.decode(bytes, clazz);
    }
    
    public static <T extends Serializable> byte[] encode(T obj, SerializationType serializationType) {
    	if(serializationType == null) {
    		return serializationOperator.encode(obj);
    	} else if(serializationType == SerializationType.JSON) {
    		SerializationOperator serializationOperator = ExtensionLoader.getExtensionLoader(SerializationOperator.class).getExtension(serializationType.getType());
    		return serializationOperator.encode(obj);
    	} else {
    		return serializationOperator.encode(obj);
    	}
    }
    
    public static <T extends Serializable> T decode(byte[] bytes, Class<T> clazz, SerializationType serializationType) {
    	if(serializationType == null) {
    		return serializationOperator.decode(bytes, clazz);
    	} else if(serializationType == SerializationType.JSON) {
    		SerializationOperator serializationOperator = ExtensionLoader.getExtensionLoader(SerializationOperator.class).getExtension(serializationType.getType());
    		return serializationOperator.decode(bytes, clazz);
    	} else { 
    		return serializationOperator.decode(bytes, clazz);
    	}
    }
    
    public static <T extends Serializable> T decode(byte[] bytes, Class<T> clazz, SerializationType serializationType, Class<?>... genericsClasses) {
    	if(serializationType == null) {
    		return serializationOperator.decode(bytes, clazz, genericsClasses);
    	} else if(serializationType == SerializationType.JSON) {
    		SerializationOperator serializationOperator = ExtensionLoader.getExtensionLoader(SerializationOperator.class).getExtension(serializationType.getType());
    		return serializationOperator.decode(bytes, clazz, genericsClasses);
    	} else { 
    		return serializationOperator.decode(bytes, clazz, genericsClasses);
    	}
    }

}
